import SwiftUI
import PhotosUI

struct ReceiptCaptureView: View {
    @State private var selectedItem: PhotosPickerItem?
    @State private var selectedImageData: Data?

    @State private var uploadedURL: String?
    @State private var parsedResult: ExpenseAIResponse?
    @State private var error: String?
    @State private var isLoading = false
    @State private var navigate = false

    var body: some View {
        NavigationStack {

            ScrollView(showsIndicators: false) {
                VStack(spacing: 28) {

                    VStack(spacing: 6) {
                        Text("Scan Receipt")
                            .font(.largeTitle.bold())
                            .foregroundColor(.primary)

                        Text("Upload a receipt to auto-extract details")
                            .font(.subheadline)
                            .foregroundColor(.secondary)
                    }
                    .padding(.top, 20)


                    PhotosPicker(selection: $selectedItem, matching: .images) {
                        HStack(spacing: 12) {
                            Image(systemName: "camera.fill")
                                .font(.title3)
                            Text("Upload or Take Photo")
                                .font(.headline)
                        }
                        .foregroundColor(.white)
                        .padding()
                        .frame(maxWidth: .infinity)
                        .background(
                            LinearGradient(colors: [Color.blue, Color.purple],
                                           startPoint: .topLeading,
                                           endPoint: .bottomTrailing)
                        )
                        .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                        .shadow(color: .purple.opacity(0.25), radius: 10, y: 6)
                        .padding(.horizontal)
                    }
                    .onChange(of: selectedItem) { newItem in
                        Task { await loadImage(from: newItem) }
                    }


                    if let data = selectedImageData,
                       let uiImage = UIImage(data: data) {

                        ZStack {
                            RoundedRectangle(cornerRadius: 20)
                                .fill(Color(.secondarySystemBackground).opacity(0.8))
                                .shadow(radius: 8, y: 4)

                            VStack(spacing: 12) {
                                Image(uiImage: uiImage)
                                    .resizable()
                                    .scaledToFit()
                                    .clipShape(RoundedRectangle(cornerRadius: 14))
                                    .padding(10)

                                Divider()

                                Text("Preview")
                                    .font(.subheadline)
                                    .foregroundColor(.secondary)
                            }
                            .padding()
                        }
                        .padding(.horizontal)
                        .transition(.scale)
                    }

                    if isLoading {
                        ProgressView("Analyzing Receipt…")
                            .font(.headline)
                            .padding(.top, 10)
                    }

                    if let error = error {
                        Text(error)
                            .foregroundColor(.red)
                            .padding(.horizontal)
                            .multilineTextAlignment(.center)
                    }

                    Button {
                        Task { await analyze() }
                    } label: {
                        Text("Analyze Receipt")
                            .font(.headline)
                            .foregroundColor(.white)
                            .padding()
                            .frame(maxWidth: .infinity)
                            .background(Color.blue)
                            .clipShape(RoundedRectangle(cornerRadius: 16))
                            .shadow(color: .blue.opacity(0.3), radius: 10, y: 5)
                            .padding(.horizontal)
                    }
                    .disabled(selectedImageData == nil || isLoading)
                    .opacity(selectedImageData == nil ? 0.5 : 1)

                    Spacer(minLength: 40)
                }
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(.systemGray6),
                        Color(.systemGray5).opacity(0.4),
                        Color.white
                    ],
                    startPoint: .top,
                    endPoint: .bottom
                )
                .ignoresSafeArea()
            )

            .navigationDestination(isPresented: $navigate) {
                if let parsedResult {
                    ReceiptDetailsView(receipt: parsedResult)
                }
            }
        }
    }

    func loadImage(from item: PhotosPickerItem?) async {
        guard let item else { return }
        do {
            if let data = try await item.loadTransferable(type: Data.self) {
                withAnimation { selectedImageData = data }
            }
        } catch {
            self.error = "Failed to load image."
        }
    }

    func analyze() async {
        guard let data = selectedImageData else {
            self.error = "No image selected."
            return
        }

        isLoading = true
        error = nil
        uploadedURL = nil
        parsedResult = nil

        do {
            let url = try await ImageUploadService.shared.uploadImage(data: data)
            self.uploadedURL = url

            let result = try await ReceiptAnalyzer.shared.analyzeReceipt(imageURL: url)
            self.parsedResult = result

            withAnimation {
                self.navigate = true
            }
        } catch {
            self.error = error.localizedDescription
        }

        isLoading = false
    }
}
